<template>
  <el-dialog :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="settingUserRef" :model="form" label-width="120px">
      <el-checkbox-group v-model="userIds">
        <el-checkbox v-for="(user,index) in sysUsers" :key="index" :label="user.userId">{{ user.userName + ' ' + user.nickName }}</el-checkbox>
      </el-checkbox-group>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="UserRelation">
import { getSubscribeRelation, saveSubscribeRelation } from "@/api/coal/messageSourceRelation";

const props = defineProps({
  messageSourceId: {
    type: Number,
    default: null,
  },
  open:{
    type:Boolean,
    default: false,
  },
})
const emit = defineEmits(['closeSettingUser']);
const open = ref(props.open)

const { proxy } = getCurrentInstance();

const title = ref('设置人员订阅')
const sysUsers = ref([])
const userIds = ref([])

const data = reactive({
  form: {},
});

const { form } = toRefs(data);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["settingUserRef"].validate(valid => {
    if (valid) {
      if (userIds.value.length > 0){
        saveSubscribeRelation({'messageSourceId':props.messageSourceId,'userIds':userIds.value}).then(resp=>{
          proxy.$modal.msgSuccess("设置完成");
          cancel()
        })
      } else {
        proxy.$modal.msgError("至少选择一个用户");
      }
    }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  emit('closeSettingUser');
  //reset();
}
onMounted(() => {
  getSubscribeRelation(props.messageSourceId).then(resp=>{
    sysUsers.value = resp.data.sysUsers
    userIds.value = resp.data.userIds
  })
})

</script>
